﻿using System;
using System.Collections.Generic;

namespace GxFramework
{
    public static class ListPool<T>
    {
        static int _countAll;
        static readonly Stack<List<T>> _stack = new Stack<List<T>>();

        static public int countAll { get { return _countAll; } }
        static public int countActive { get { return countAll - countInactive; } }
        static public int countInactive { get { return _stack.Count; } }
        static public List<T> Get(int capacity=0)
        {
            List<T> ret = null;
            if (_stack.Count == 0)
            {
                ret = new List<T>(capacity);
                ++_countAll;
            }
            else
                ret = _stack.Pop();
            return ret;
        }
        static public void Release(List<T> item)
        {
            if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), item))
                throw new Exception("[ListPool] Internal error. Trying to release List that is already released to pool.");
            item.Clear();
            _stack.Push(item);
        }
        static public void Put(List<T> item)
        {
            if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), item))
                throw new Exception("[ListPool] Internal error. Trying to put List that is already released to pool.");
            _stack.Clear();
            _stack.Push(item);
            ++_countAll;
        }
        static public void Clear()
        {
            _stack.Clear();
            _countAll = 0;
        }
        static public void Clear(int reserveCount)
        {
            while (_stack.Count > reserveCount)
            {
                --_countAll;
                var item = _stack.Pop();
                item.Clear();
            }
        }
    }
}